package com.example.studentmanagement2.service.Impl;


import com.example.studentmanagement2.model.User;
import com.example.studentmanagement2.repository.Repository.LoginRepository;
import com.example.studentmanagement2.service.LoginService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;

@Service
public class LoginServiceImpl implements LoginService {

    private static final Logger logger = LoggerFactory.getLogger(LoginServiceImpl.class);

    @Autowired
    private LoginRepository loginRepository;

    @Autowired
    private PasswordEncoder passwordEncoder;

    @Override
    public User authenticate(String username, String password) {
        logger.info("===== 登录验证开始 =====");
        logger.info("输入用户名: {}", username);

        // 打印PasswordEncoder类型
        logger.info("PasswordEncoder类型: {}", passwordEncoder.getClass().getName());

        User user = loginRepository.findByUsername(username);

        if (user == null) {
            logger.error("用户不存在: {}", username);
            logger.info("===== 登录验证结束（用户不存在） =====");
            throw new RuntimeException("Invalid credentials");
        }

        logger.info("查询到用户: ID={}, 用户名={}, 角色={}",
                user.getId(), user.getUsername(), user.getRole());
        logger.info("数据库密码: {}", user.getPassword());
        logger.info("输入密码: {}", password);

        // 测试密码编码器
        String testEncoded = passwordEncoder.encode("test");
        logger.info("测试密码编码: {}", testEncoded);

        boolean matches = passwordEncoder.matches(password, user.getPassword());
        logger.info("密码匹配结果: {}", matches);

        if (!matches) {
            logger.error("密码不匹配");
            logger.info("===== 登录验证结束（密码错误） =====");
            throw new RuntimeException("Invalid credentials");
        }

        logger.info("登录成功: {}", username);
        logger.info("===== 登录验证结束 =====");
        return user;
    }
}